//
//  LessonTeacherViewController.m
//  LoveDraw
//
//  Created by 零零壹 on 2017/7/13.
//  Copyright © 2017年 梁晨. All rights reserved.
//

#import "LessonTeacherViewController.h"
#import "LessonShareTableViewCell.h"
#import "CellForWorkGroup.h"
#import "UITableViewCell+HYBMasonryAutoCellHeight.h"
#import "AddLessonShareViewController.h"

@interface LessonTeacherViewController ()<UITableViewDelegate,UITableViewDataSource,CellForWorkGroupDelegate,AddDataReloadData>
{
    NSInteger page;
}
@property(nonatomic,strong)UITableView *ListV;
@property(nonatomic,strong)NSMutableArray *ListArr;
@property (nonatomic,strong) NSMutableDictionary *heightDict;
//@property (nonatomic,strong) NSIndexPath *indexPath;
@property(nonatomic,strong) NSMutableArray *requestArr;
@property(nonatomic,strong)NSMutableArray *firstArr;

@end

@implementation LessonTeacherViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.ListV];

    UIButton *rightbutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    rightbutton.frame= CGRectMake(0, 10, 44, 44);
    rightbutton.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, -10);
    [rightbutton addTarget:self action:@selector(rightOnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarbutton = [[UIBarButtonItem alloc] initWithCustomView:rightbutton];
    [rightbutton setImage:[[UIImage imageNamed:@"publish"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:(UIControlStateNormal)];
    self.navigationItem.rightBarButtonItem = leftBarbutton;

    self.ListV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        page = 1;
        [self requestDataLoadNew:YES];
    }];
    self.ListV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        page++;
        [self requestDataLoadNew:YES];
    }];

    [self.ListV.mj_header beginRefreshing];

}

-(void)rightOnClick
{
    AddLessonShareViewController *VC = [[AddLessonShareViewController alloc]init];
    VC.Delegate = self;
    [self.navigationController pushViewController:VC animated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.navigationItem.title = @"课例管理";
}

#pragma mark --- 懒加载
-(UITableView *)ListV
{
    if (!_ListV) {
        _ListV = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KscreenW, KscreenH-64) style:(UITableViewStyleGrouped)];
        _ListV.delegate = self;
        _ListV.dataSource = self;
        _ListV.backgroundColor = [UIColor whiteColor];
        _ListV.separatorStyle = 0;
        _ListV.estimatedSectionHeaderHeight = 0;
        _ListV.estimatedSectionFooterHeight = 0;
        [_ListV registerClass:[LessonShareTableViewCell class] forCellReuseIdentifier:@"LessonShareTableViewCell"];
        [_ListV registerClass:[CellForWorkGroup class] forCellReuseIdentifier:NSStringFromClass([CellForWorkGroup class])];
    }
    return _ListV;
}
- (NSMutableDictionary *)heightDict{
    if (!_heightDict) {
        _heightDict = [NSMutableDictionary new];
    }
    return _heightDict;
}
-(NSMutableArray *)ListArr
{
    if (!_ListArr) {
        _ListArr = [NSMutableArray array];
    }
    return _ListArr;
}

-(NSMutableArray *)requestArr
{
    if (!_requestArr) {
        _requestArr = [NSMutableArray array];
    }
    return _requestArr;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.ListArr.count == 0) {
        self.ListV.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"nodata"]];
    }else
    {
        self.ListV.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@""]];
    }
    return self.ListArr.count;;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YHWorkGroup *model  = self.ListArr[indexPath.row];
    CellForWorkGroup *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CellForWorkGroup class])];
    if (!cell) {
        cell = [[CellForWorkGroup alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([CellForWorkGroup class])];
    }
    cell.indexPath = indexPath;
    cell.model     = model;
    cell.delegate  = self;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < self.ListArr.count)
    {
        CGFloat height = 0.0;
        YHWorkGroup *model  = self.ListArr[indexPath.row];

        //取缓存高度
        NSDictionary *dict =  self.heightDict[model.dynamicId];

        if (dict) {
            if (model.isOpening) {
                height = [dict[@"open"] floatValue];
            }else{
                height = [dict[@"normal"] floatValue];
            }
            if (height) {
                return height;
            }
        }

        height = [CellForWorkGroup hyb_heightForTableView:tableView config:^(UITableViewCell *sourceCell) {
            CellForWorkGroup *cell = (CellForWorkGroup *)sourceCell;
            cell.model = model;
        }];

        //缓存高度
//        if (model.dynamicId) {
//            NSMutableDictionary *aDict = [NSMutableDictionary new];
//            if (model.isOpening) {
//                [aDict setObject:@(height) forKey:@"open"];
//            }else{
//                [aDict setObject:@(height) forKey:@"normal"];
//            }
//            [self.heightDict setObject:aDict forKey:model.dynamicId];
//        }
        return height;
    }else{
        return 44.0f;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return FLT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return FLT_MIN;
}

#pragma mark - 网络请求
- (void)requestDataLoadNew:(BOOL)loadNew
{
    if (self.cid)
    {

    }else
    {
        self.cid = @"";
    }

    [RequestManager RequstWithUrl:@"/index.php?g=App&m=TeacherCourseep&a=index" parmDic:@{@"cid":self.cid,@"page":[NSString stringWithFormat:@"%ld",page],@"tid":[[NSUserDefaults standardUserDefaults]objectForKey:@"tid"]} requestType:RequestGET Success:^(id data)
     {
        self.firstArr = [data mutableCopy];

         if (page == 1) {
             [self.requestArr removeAllObjects];
             [self.ListArr removeAllObjects];
         }
         if (self.firstArr.count==0)
         {
             page--;
         }

         [self.requestArr addObjectsFromArray:self.firstArr];

         [self.ListV.mj_footer endRefreshing];
         [self.ListV.mj_header endRefreshing];

         if (self.firstArr.count == 0||self.firstArr.count<10)
         {
             self.ListV.mj_footer.state = MJRefreshStateNoMoreData;
         }

         NSInteger totalCount = self.firstArr.count;
         NSUInteger lastDynamicID = 0;

         if (!loadNew && self.requestArr .count) {
             YHWorkGroup *model = self.requestArr.lastObject;
             lastDynamicID = [model.dynamicId integerValue];
         }
         
         for (int i=0; i<totalCount; i++)
         {
             YHWorkGroup *model = [YHWorkGroup new];
             model.dynamicId = [NSString stringWithFormat:@"%lu", lastDynamicID + i+1];
             [self randomModel:model totalCount:i];
             [self.ListArr addObject:model];
         }
         NSLog(@"%ld",self.ListArr.count);

         [self.ListV reloadData];
     } error:^(NSError *error) {

     }];

  }

- (void)randomModel:(YHWorkGroup *)model totalCount:(NSInteger)totalCount{
    [self creatOriModel:model totalCount:totalCount];
}

- (void)creatOriModel:(YHWorkGroup *)model totalCount:(NSInteger)totalCount{

    NSDictionary *dic = self.firstArr[totalCount];
    
    model.msgContent = dic[@"title"];
    model.title = dic[@"coursename"];
    model.bottomLeft = dic[@"addtimedesc"];
    model.bottomRight = dic[@"teachername"];
    model.avatar = dic[@"teacherthumb"];

    //原图
    NSArray *thumbsArr = dic[@"thumbs"];

    NSArray *Bigimage = thumbsArr;

    NSMutableArray *oriPName = [NSMutableArray array];

    for (NSString *imageUrlStr in Bigimage)
    {
        
        [oriPName addObject:[NSString stringWithFormat:@"%@%@",KUrl,imageUrlStr]];
    }

    NSMutableArray *oriPArr = [NSMutableArray new];
    for (NSString *pName in oriPName) {
        [oriPArr addObject:[NSURL URLWithString:pName]];
    }

    //小图
    NSArray *smallArr =dic[@"thumbs"];
    NSMutableArray *thumbPName = [NSMutableArray array];

    for (NSString *smallPic in smallArr)
    {
        NSString *small = [NSString stringWithFormat:@"%@%@",KUrl,smallPic];

        [thumbPName addObject:[small stringByReplacingOccurrencesOfString:@"/thumb" withString:@""]];
    }

    NSMutableArray *thumbPArr = [NSMutableArray new];
    for (NSString *pName in thumbPName) {
        [thumbPArr addObject:[NSURL URLWithString:pName]];
    }

    model.originalPicUrls = thumbPArr;
    model.thumbnailPicUrls =oriPArr ;

}

-(void)AddDataReloadData
{
    [self requestDataLoadNew:YES];
}

#pragma mark - CellForWorkGroupDelegate
- (void)onAvatarInCell:(CellForWorkGroup *)cell
{

}

- (void)onMoreInCell:(CellForWorkGroup *)cell{
    if (cell.indexPath.row < [self.ListArr count]) {
        YHWorkGroup *model = self.ListArr[cell.indexPath.row];
        model.isOpening = !model.isOpening;
        [self.ListV reloadRowsAtIndexPaths:@[cell.indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void)onDeleteInCell:(CellForWorkGroup *)cell
{
    NSIndexPath *indexpath = [self.ListV indexPathForCell:cell];

        [self _deleteDynAtIndexPath:indexpath dynamicId:cell.model.dynamicId];
    

}

#pragma mark - private
- (void)_deleteDynAtIndexPath:(NSIndexPath *)indexPath dynamicId:(NSString *)dynamicId
{
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"消息提示框" message:@"是否删除本条消息" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    UIAlertAction *commit = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action)
    {
        [self ShanChuindexpath:indexPath];
    }];
    [ac addAction:cancel];
    [ac addAction:commit];
    [self presentViewController:ac animated:YES completion:nil];
}

-(void)ShanChuindexpath:(NSIndexPath *)indexpath
{
    NSDictionary *ModelDic = self.requestArr[indexpath.row];
    NSLog(@"%ld",indexpath.row);
    [RequestManager HudRequestWithUrl:@"/index.php?g=App&m=TeacherCourseep&a=deleteEp" parmDic:@{@"tid":[[NSUserDefaults standardUserDefaults]objectForKey:@"tid"],@"aid":ModelDic[@"aid"]} requestType:RequestPOST view:self.view Success:^(id data)
    {
        [self.requestArr removeObjectAtIndex:indexpath.row];
        [self.ListArr removeObjectAtIndex:indexpath.row];
        [self.ListV deleteRowsAtIndexPaths:@[indexpath] withRowAnimation:(UITableViewRowAnimationFade)];
    } error:^(NSError *error)
    {

    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
